package com.m.man.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class FileOptionUtil{

    /**
     * 获取文件 的md5 码
     */
    public static String getFileMD5(String file_path) throws IOException {
//        String fileMd5 = Md5AndShaUtil.getMD5ofFileSimple(file_path);
        FileInputStream in = new FileInputStream(file_path);

        String fileMd5 = DigestUtils.md5DigestAsHex(in);
        in.close();
        return fileMd5;
    }

    /**
     * 获取  文件的修改时间
     */
    public static String getFileUpdateTimeSimple(String file_path){
        File file = new File(file_path);

        long time = file.lastModified();

        return TimeUtil.getFormartTime(time);
        //一种输出方法
//		cal.setTimeInMillis(time);
//		cal.getTime().toLocaleString();
        //另一种输出方法

    }

    /**
     * 获取  文件的修改时间
     */
    public static void getFileUpdateTime(String file_path){
        BasicFileAttributes battriAttributes = null;
        File file = new File(file_path);
        try {
            battriAttributes =
                    Files.readAttributes(file.toPath(),BasicFileAttributes.class);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 修改时间
        String updateTime = battriAttributes.lastModifiedTime().toString();
    }


    /**
     * 获取文件大小
     */
    public static long getFileSize(String file_path){
        File file = new File(file_path);
        if(!file.exists() && !file.isFile()){
            System.out.println(file_path + "\t文件不存在或不是文件");
            return -1;
        }
        return file.length();
    }

    /**
     * 获取  某个  目录下的所有文件  的绝对路径
     * @param path
     */
    public static List<String> getAllfileFullPath(String path){
        File file = new File(path);

        if( !file.isDirectory()){
            List<String> l = new ArrayList<String>();
            l.add(path);
            return  l;
        }else if( file.isDirectory()){
            List<String> l = new ArrayList<String>();
            File[] fileArray = file.listFiles(); // 所有文件和文件夹的  绝对路径
            for(int i = 0 ; i < fileArray.length;i++){
                try{
                    l.addAll(getAllfileFullPath(fileArray[i].toString()));
                }catch(Exception e){
                    System.out.println(fileArray[i]+"<<报错了");
                }
            }

            return l;
        }else{
            System.out.println(file +"\t是空======================");
            return null;
        }
    }
    /**
     * 根据 绝对路径获取  文件名字
     */
    public String getFileName(String path){
        return new File(path).getName();
    }
    /**
     * 根据  文件路径  获取  后缀名
     */
    public static String getFileType(String path){
        String fileName = new File(path).getName();
        String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length())  ;
        return fileType;
    }

    /**
     *  复制  文件  fileChannels
     */
    public static long copFileFileChannels(File oldFile,File newFile){
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(oldFile).getChannel();
            outputChannel = new FileOutputStream(newFile).getChannel();
            long k = outputChannel.transferFrom(inputChannel, 0,inputChannel.size());
            return k;
//            if (k > 0){
//                return true;
//            }else {
//                return false;
//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }finally {
            try {
                if ( inputChannel != null ){
                    inputChannel.close();
                }
                if ( outputChannel != null) {
                    outputChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 复制文件
     */
    public static int copyFile(File oldFile,File newFile) throws IOException {

        int result = FileCopyUtils.copy  (oldFile, newFile);
        System.out.println("复制文件======"+result);
        return result;
    }

    public static void main(String[] args) throws IOException {
        String of = "F:\\workspace\\idea\\man\\src\\main\\resources\\static\\story\\file\\txt\\中华网_2019_09_15.txt";
        String nf = "F:\\workspace\\idea\\man\\src\\main\\resources\\static\\story\\out\\txt\\2019_09_15\\中华网_2019_09_15.txt";
//        copyFile(new File(of),new File(nf));
        deleteFile(new File(of));
    }

    /***
     * 删除文件
     */
    public static  boolean deleteFile(File file){
        if (file.exists() && file.isFile()) {//文件是否存在
            try{
                boolean flag = file.delete();
                if (flag == true) {//存在就删了，返回1
                    System.out.println("删除ss文件=="+true);
                    return true;
                } else {
                    System.out.println("删除ss文件=="+false);
                    boolean k = file.delete();
                    if(k == true){
                        System.out.println("第二次删除成功");
                    }else {
                        System.out.println("第二次删除失败");
                    }
                    return false;
                }
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }

        } else {
            return true;
        }
    }

    /**
     * 根据行 读取文件   返回每行为一个元素的list
     * @param path
     * @return
     * @throws UnsupportedEncodingException
     * @throws FileNotFoundException
     */
    public static List<String> readFileLine2List(String path) throws UnsupportedEncodingException, FileNotFoundException{
        BufferedReader in = null;
        String str = "";
        List<String> resp = new ArrayList<String>() ;
        int i = 0;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(path),"utf-8" ));
            while((str = in.readLine() ) != null){
                resp.add(str);
            }
            System.out.println("文本读取完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(null != in){
                    in.close();
                    return resp;
                }else{
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 根据行 读取文件
     * @param path
     * @return
     * @throws UnsupportedEncodingException
     * @throws FileNotFoundException
     */
    public static String readFileLine(String path) throws UnsupportedEncodingException, FileNotFoundException{
        BufferedReader in = null;
        String str = "";
        String resp = "" ;
        int i = 0;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(path),"utf-8" ));
            while((str = in.readLine() ) != null){
                resp = resp + str;
            }
            System.out.println("文本读取完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(null != in){
                    in.close();
                    return resp;
                }else{
                    return null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static Long readFile_readLine_length(String path){
        long strCount = 0L;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            String lineStr = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((lineStr = reader.readLine()) != null) {
                // 显示行号
//                System.out.println("line " + line + ": " + lineStr);
//                line++;
//				System.out.println(count);
//				lineStr = lineStr+lineStr
                strCount = strCount ;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  finally{
            if(null != reader){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return strCount;
    }

    /**
     * 读取文件(字节流)
     * 以字符为单位读取文件，常用于读文本，数字等类型的文件
     */
    public static Long readFile_InputStreamReader_length(String path){
        long strCount = 0L;
        Reader in = null;
        try {
            in = new InputStreamReader(new FileInputStream(path),"utf-8");
            //循环取出数据
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = in.read()) != -1) {
                strCount = strCount + len;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return strCount;
    }

    /**
     * 缓存字节流计算文件字数  使用方式和字节流差不多，但是效率更高（推荐使用）
     */
    public static Long readFile_BufferedInputStream_length(String path){
        long strCount = 0L;
        //读取文件(缓存字节流)
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));
            byte [] bytes = new byte[2048];
//			byte [] bytes = new byte[10240];
            int n = -1;
            while((n = in.read(bytes, 0, bytes.length)) != -1){
                //转换成字符串
                String str = new String(bytes, 0, n,"UTF-8");
                strCount = strCount + str.split("").length;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return strCount;
    }

    /**
     * 字节流的方式 计算文件 字数
     * 以字节为单位读取文件，常用于读二进制文件，如图片、声音、影像等文件。
     * @param path
     * @return
     */
    public static Long readFile_FileInputStream_length(String path){
        Long strCount = 0L;
        InputStream inputStream = null;
        try {
            //读取文件(字节流)
            inputStream = new FileInputStream(path);
            //一次性取多少字节
            byte[] bytes = new byte[2048];
            //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
            int n = -1;

            while((n = inputStream.read(bytes,0,bytes.length))!= -1){
                //转换成字符串
                String str = new String(bytes, 0, n,"UTF-8");
                strCount = strCount + str.length();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strCount;
    }

    /**
     * 创建目录和文件
     */
    public static boolean mkFile(String filePath){
        try {
            File file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            if(file.exists()){
                return true;
            }else{
                return false;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建路径
     */
    public static boolean mkDir(String dirPath){
        File dir = new File(dirPath);
        if(! dir.exists() ){
            dir.mkdir();
            if(dir.exists()){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }
}
